package com.vic.framework.helper;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;

import com.vic.framework.annotation.Action;
import com.vic.framework.bean.Handle;
import com.vic.framework.bean.Request;

/**
 * 控制器辅助类
 * @author VIC
 *
 */
public final class Controllerhelper {

	/**
	 * 存放请求和处理器的映射关系
	 */
	public static final Map<Request, Handle> ACTION_MAP = new HashMap<Request, Handle>();

	static {
		//全部的controller
		Set<Class<?>> controllerSet =  ClassHelper.getControllerClassSet();
		
		if(CollectionUtils.isNotEmpty(controllerSet)) {
			for(Class<?> controllerClass : controllerSet) {
				Method[] methods = controllerClass.getDeclaredMethods();
				if(ArrayUtils.isNotEmpty(methods)) {
					for(Method method : methods) {
						//如果方法上加了Action注解
						if(method.isAnnotationPresent(Action.class)) {
							Action action = method.getAnnotation(Action.class);
							String mapping = action.value();
							if(mapping != null && mapping.matches("\\w+:/\\w*")) {
								String[] arr = mapping.split(":");
								if(arr != null && arr.length == 2) {
									Request request = new Request(arr[0], arr[1]);
									Handle handle = new Handle(controllerClass, method);
									ACTION_MAP.put(request, handle);
								}
							}
							
						}
					}
				}
			}
		}
	}
	
	
	public static Handle getHandle(String requestMethod, String requestPath) {
		return ACTION_MAP.get(new Request(requestMethod, requestPath));
	}
}
